/**
 * Created by chengcong on 2017/11/21.
 */
$('.return').on('click',function (e) {
    window.history.back();
});
var category='';
var arr=location.search.split("=");
console.log(arr);
var arr2=arr[1].split('&&');//0=医生待处理，1=医生已处理，2=药师待处理，3=药师已处理
// const sokceturl = "http://47.90.123.205:8000";


$('.savebtn').on('click',function () {
    var now=new Date();
    var y=now.getFullYear();
    var m=now.getMonth()+1;
    var d=now.getDate();
    if($('.toptop p').html()==undefined)$('.toptop').append('<p><span>编号：89757</span><span class="text-right">'+y+'年'+m+'月'+d+'日</span></p>');
});
var msg=window.sessionStorage['user_msg'];
msg=JSON.parse(msg);
if(msg.userrole==1){
    $('.btn3').parent('span').remove();
}
var msg=window.sessionStorage['user_msg'];
msg=JSON.parse(msg);
console.log(msg);
var doclist='';
$(function(){
    socket.emit('login',{
        token:msg.token,
        username :msg.username,
        openid  :null,
        sex : 0,
        marking :1,//1pc  2wx  3app  Number
        userrole :msg.userrole//登陆角色 (医生(1)，用户(2)，助理(3)，药师(4),匿名用户(5))
    });
    $.ajax({
        url:url+'/server/mes',
        type:'post',
        data:{
            _id: arr2[0]
        },
        headers: {
            'Authorization': 'Bearer ' + msg.token
        },
        success:function (data) {
            console.log(data);
            var detailmsg='';
            if(data.code==200){
                detailmsg=data.data;
            }else{
                alert(data.mes)
            }
            console.log(detailmsg);
            //基本信息渲染
            $('.savedoc').attr('listid',arr2[0]);
            $('.name').text(detailmsg.name);
            $('.age').text(detailmsg.birthday);
            $('.sex').text(detailmsg.gender==true?'男':'女');
            $('.height').text(detailmsg.height);
            $('.weight').text(detailmsg.weight);
            $('.dochis').text(detailmsg.allergy);
            $('.medicine').text(detailmsg.medicalHistory);
            $('.basicbtn').attr('detailid',detailmsg._id);
            $('.serresult').text(detailmsg.serverSuggest);
            $('.assresult').text(detailmsg.systemResult);
            $('.savebtn').attr('listid',detailmsg._id);
            $('.savebtn').attr('userid',detailmsg.userid);
            $('.btn3').attr('listid',detailmsg._id);
            $('.txtresult textarea').val(detailmsg.diagnosisResult);
            //签名渲染
            if(detailmsg.assistantName&&detailmsg.doctorName){
                $('.docname').html('<span>'+detailmsg.doctorName+'</span><span>/'+detailmsg.assistantName+'助理</span>');
            }else if(detailmsg.doctorName){
                $('.docname').html('<span>'+detailmsg.doctorName+'</span>');
            }else if(detailmsg.assistantName){
                $('.docname').html('<span>'+detailmsg.assistantName+'助理</span>');
            }
            $('.basicbtn').on('click',function (e) {
                self.location='basicpaper.html?detailId='+$(e.target).attr('detailid');
            });
            //药品渲染
            $('.medic').html('');
            const  medicinal=detailmsg.docMedicinal||detailmsg.assMedicinal||detailmsg.serMedicinal;
            if(medicinal.OTC.length>0){
                for(var j=0;j<medicinal.OTC.length;j++){
                    $('.medic').append('<span><b pid="'+medicinal.OTC[j].productid+'" isdrugstatus="N" dataimg="'+medicinal.OTC[j].img+'" datamarket="'+medicinal.OTC[j].marketprice+'" dataprice="'+medicinal.OTC[j].costprice+'">'+medicinal.OTC[j].productname
                        +'</b><input type="number" min="1" value="'+medicinal.OTC[j].count+'"><a class="btn delbtn">删除</a></span>');
                }
            }
            if(medicinal.Rx_Drug.length>0){
                for(var j=0;j<medicinal.Rx_Drug.length;j++){
                    $('.medic').append(' <span><b pid="'+medicinal.Rx_Drug[j].productid+'" isdrugstatus="Y" dataimg="'+medicinal.Rx_Drug[j].img+'" datamarket="'+medicinal.Rx_Drug[j].marketprice+'" dataprice="'+medicinal.Rx_Drug[j].costprice+'">'+medicinal.Rx_Drug[j].productname
                        +'</b><input type="number" min="1" value="'+medicinal.Rx_Drug[j].count+'"><a class="btn delbtn">删除</a></span>');

                }
            }
            if(arr[2]=="3"){
                $('.btn').remove();
                if(detailmsg.result==false)detailmsg.result='不通过';
                if(detailmsg.result==true)detailmsg.result='通过';

                $('.check').html('<span>药师签名：'+detailmsg.pharmacistName+'</span><span>审核结果：'
                    +detailmsg.result+'</span><span>审核时间：'+detailmsg.phaTime+'</span>  ')
            }
            $('.delbtn').on('click',function (e) {
                $(e.target).parent('span').remove();
            })
            if(arr[2]=='0'){

            }else{
                $('.txtresult').html('');
                $('.txtresult').text(detailmsg.diagnosisResult);
                $('input').attr('readonly','readonly');
            }
            if(detailmsg.diagnosisResult&&detailmsg.record.length==0){
                $('.txtresult').text(detailmsg.diagnosisResult);
            }
            if(arr[2]=="1"){
                $('.btn').remove();
                $('.check').append('<span><button class="btn prebtn">上一张</button> <button class="btn nextbtn">下一张</button></span>')
            }
            if(arr[2]=="2"){
                $('.btn').remove();
                $('.check').html('<span><button class="btn checkbtn" result="1" listid="'+detailmsg._id+'" userid="'+detailmsg.userid+'"  doctorName="'+detailmsg.doctorName+'">通过</button></span>' +
                    '<span><button class="btn btn3 checkbtn" result="0" listid="'+detailmsg._id+'" userid="'+detailmsg.userid+'"  doctorName="'+((detailmsg.doctorId)==null?detailmsg.assistantName:detailmsg.doctorName)+'">不通过</button></span>')
            }
            //详情上一张下一张
            $('.prebtn').on('click',function () {
                if(arr2[1]=='type'){
                    $.ajax({
                        url:url+'/server/assDocFinish',
                        type:'post',
                        data:{
                            id: msg.userid,
                            userRole: msg.userrole
                        },
                        headers: {
                            'Authorization': 'Bearer ' + msg.token
                        },
                        success:function (data) {
                            console.log(data);
                            if(data.code==200){
                                $('table tbody').html('');
                                if(data.data.length>0){
                                    var finishlist=[];
                                    data.data=data.data.sort(compare("docTime"));
                                    for(var k=0;k<data.data.length;k++){
                                        finishlist.unshift(data.data[k]);
                                    }
                                    console.log(finishlist);
                                    for(var i=0;i<finishlist.length;i++) {
                                        if (finishlist[i]._id == detailmsg._id){
                                            if(i>0){
                                                self.location = 'postpaper.html?detailId=' + finishlist[i-1]._id + '&&type=' + 1;
                                            }else{
                                                alert('已经到头了')
                                            }
                                        }
                                    }
                                }
                            }else{
                                alert(data.mes)
                            }
                        }
                    });
                }else{
                    $.ajax({
                        url:url+'/server/assDocFinish',
                        type:'post',
                        data:{
                            id: arr2[1],
                            userRole: 6
                        },
                        headers: {
                            'Authorization': 'Bearer ' + msg.token
                        },
                        success:function (data) {
                            console.log(data);
                            if(data.code==200){
                                $('table tbody').html('');
                                if(data.data.length>0){
                                    var finishlist=[];
                                    data.data=data.data.sort(compare("docTime"));
                                    for(var k=0;k<data.data.length;k++){
                                        finishlist.unshift(data.data[k]);
                                    }
                                    console.log(finishlist);
                                    for(var i=0;i<finishlist.length;i++) {
                                        if (finishlist[i]._id == detailmsg._id){
                                            if(i>0){
                                                self.location = 'postpaper.html?detailId=' + finishlist[i-1]._id + '&&type=' + 1;
                                            }else{
                                                alert('已经到头了')
                                            }
                                        }
                                    }
                                }
                            }else{
                                alert(data.mes)
                            }
                        }
                    });
                }
            });
            $('.nextbtn').on('click',function () {
                if(arr2[1]=='type'){
                    $.ajax({
                        url:url+'/server/assDocFinish',
                        type:'post',
                        data:{
                            id: msg.userid,
                            userRole: msg.userrole
                        },
                        headers: {
                            'Authorization': 'Bearer ' + msg.token
                        },
                        success:function (data) {
                            console.log(data);
                            if(data.code==200){
                                $('table tbody').html('');
                                if(data.data.length>0){
                                    var finishlist=[];
                                    data.data=data.data.sort(compare("docTime"));
                                    for(var k=0;k<data.data.length;k++){
                                        finishlist.unshift(data.data[k]);
                                    }
                                    console.log(finishlist);
                                    for(var i=0;i<finishlist.length;i++) {
                                        if (finishlist[i]._id == detailmsg._id){
                                            if(i<finishlist.length-1){
                                                self.location = 'postpaper.html?detailId=' + finishlist[i+1]._id + '&&type=' + 1;
                                            }else{
                                                alert('没有更多了')
                                            }
                                        }
                                    }
                                }
                            }else{
                                alert(data.mes)
                            }
                        }
                    });
                }else{
                    $.ajax({
                        url:url+'/server/assDocFinish',
                        type:'post',
                        data:{
                            id: arr2[1],
                            userRole: 6
                        },
                        headers: {
                            'Authorization': 'Bearer ' + msg.token
                        },
                        success:function (data) {
                            console.log(data);
                            if(data.code==200){
                                $('table tbody').html('');
                                if(data.data.length>0){
                                    var finishlist=[];
                                    data.data=data.data.sort(compare("docTime"));
                                    for(var k=0;k<data.data.length;k++){
                                        finishlist.unshift(data.data[k]);
                                    }
                                    console.log(finishlist);
                                    for(var i=0;i<finishlist.length;i++) {
                                        if (finishlist[i]._id == detailmsg._id){
                                            if(i<finishlist.length-1){
                                                self.location = 'postpaper.html?detailId=' + finishlist[i+1]._id + '&&type=' + 1;
                                            }else{
                                                alert('没有更多了')
                                            }
                                        }
                                    }
                                }
                            }else{
                                alert(data.mes)
                            }
                        }
                    });
                }
            });
            //药师审核
            $('.checkbtn').on('click',function (e) {
            	if($(e.target).attr('result')==1){
            	//socket通知信息
                              socket.emit('private_data',{
                                     	dataType:"notification",
                                        userid: [$(e.target).attr('userid')],
                                        msg: '问诊单审核通过，请查看',
                                        doctorName:$(e.target).attr('doctorName'),
                                        _id: [$(e.target).attr('listid')]
                                   })
            		
            	}else{
            		for (let s=0;s<socketuser.length;s++) {
            			 if(socketuser[s].userName==$(e.target).attr('doctorName')){
            			 	console.log(socketuser[s].id);
            			 	 socket.emit('private_data',{
                                     	dataType:"notthrough",
                                        userid: [$(e.target).attr('userid')],
                                        msg: '问诊单审核不通过！',
                                        doctorName:$(e.target).attr('doctorName'),
                                        _id: [$(e.target).attr('listid')],
                                        socket_id:socketuser[s].id
                            })
            			 }
            			
            		}
            	}
            	
                $.ajax({
                    url:url+'/server/pharmacistCheck',
                    type:'post',
                    data:{
                        _id: $(e.target).attr('listid'),
                        result: $(e.target).attr('result'),
                        id: msg.userid,
                        name: msg.username
                    },
                    headers: {
                        'Authorization': 'Bearer ' + msg.token
                    },
                    success:function (data) {
                        console.log(data);
                        if(data.code==200){
                            alert(data.mes);
                            $.ajax({
                                url:url+'/server/allCertificate',
                                type:'post',
                                data:{

                                },
                                headers: {
                                    'Authorization': 'Bearer ' + msg.token
                                },
                                success:function (data) {
                                    console.log(data);
                                    if (data.code == 200) {
                                        window.top.document.getElementsByClassName('unfinish2')[0].innerHTML = data.OTC.length + data.Rx_Drug.length;
                                        // $('.unfinish').text(data.data.length)
                                        if ((data.OTC.length + data.Rx_Drug.length) > 0) {
                                            window.top.document.getElementsByClassName('unfinish2')[0].style.display = 'inline-block';
                                        } else {
                                            window.top.document.getElementsByClassName('unfinish2')[0].style.display = 'none';
                                        }
                                    }
                                }
                            })
                            $.ajax({
                                url:url+'/service/modification',
                                type:'post',
                                data:{
                                    roomname:$(e.target).attr('userid'),
                                    state:['待处理','审核通过'][$(e.target).attr('result')]
                                },
                                headers: {
                                    'Authorization': 'Bearer ' + msg.token
                                },
                                success:function (data3) {
                                    console.log(data3);
                                    if($(e.target).attr('result')==1){
                                        $.ajax({
                                            type:"post",
                                            dataType:"json",
                                            url:"https://xcx.juseyx.cn/service/producer",
                                            data:{
                                                topic: "juseservice",
                                                msg: JSON.stringify({
                                                    userid: [$(e.target).attr('userid')],
                                                    msg: '问诊单审核通过，请查看',
                                                    _id: [$(e.target).attr('listid')]
                                                }),
                                                msgkey: "key",
                                            },
                                            async:true,
                                            success:function(res){
                                                console.log(res);
                                                if(res.code==200){
                                                    self.location='postpaper.html?detailId='+$(e.target).attr('listid')+'&&status=3';
                                                }else{
                                                    alert(res.mes);
                                                }
                                            },

                                            error:function(err){
                                                console.log(err)
                                            }
                                        });
                                    }else{
                                        self.location='postpaper.html?detailId='+$(e.target).attr('listid')+'&&status=3';
                                    }
                                }
                            })
                        }else{
                            alert('操作失败');
                        }
                    }
                });
            });

        }
    });
    //添加药品分类信息
    $.ajax({
        type: "post",
        url: "https://xcxgoods.juseyx.cn/categories/GetCategoryList",
        data: {
            categoryname: "",
            isenabled: 1
        },
        success: function(res) {
            console.log(res);
            category=res.data;
            $('#category').html('<option value="">-分类-</option>')
            for(var i=0;i<res.data.length;i++){
                $('#category').append('<option value="'+res.data[i].categoryid+'">'+res.data[i].categoryname+'</option>');
            }
        },
        error: function(err) {
            console.log(err)
        }
    });
    //所有产品信息
    $.ajax({
        type: "post",
        url: "https://xcxgoods.juseyx.cn/products/GetYyReceptionGoods",
        data: {
            pagesize: 7,
            pageindex: 1,
            ReceptionSearch: $('.p_name').val(),
            brandid: null,
            isdrugstatus: null,
            SortBy: "addeddate",
            Desc: true
        },
        success: function(res) {
            console.log(res);
            $('.p_list tbody').html('');
            if(res.data.length>0){
                for(var i=0;i<res.data.length;i++){
                    $('.p_list tbody').append('<tr style="height: 50px;"><td>'+
                        res.data[i].productname+'</td><td><img  width="50px" height="50px" src="'+
                        res.data[i].goodlistimageurl+res.data[i].goodlistimagename+'" alt=""></td><td>'+
                        res.data[i].dosageformname +'</td><td>'+
                        res.data[i].brandname+'</td><td>'+
                        res.data[i].brandname+'</td>' +
                        '<td><span class="checkmed text-center" proid="'+res.data[i].productid+'" isdrugstatus="'+
                        res.data[i].isdrugstatus+'" dataimg="'+
                        res.data[i].goodlistimageurl+res.data[i].goodlistimagename+'" dataprice="'+
                        res.data[i].costprice+'" datamarket="'+
                        res.data[i].marketprice+'">+</span></td></tr>')
                }
                $('.pagecount_p').text(Math.ceil(res.datacount/7));
            }else{
                $('.p_list tbody').append('<tr><td colspan="6" class="text-center">未找到产品</td></tr>')
            }
            //确认选择商品
            $('.checkmed').on('click',function (e) {

                var lis=$('.midmed span b');
                var canpush=true;
                for(var i=0;i<lis.length;i++){
                    if($(lis[i]).attr('pid')==$(e.target).attr('proid')){
                        canpush=false;
                    }
                }
                if(canpush==false){
                    $('.midmed b[pid="'+$(e.target).attr('proid')+'"]').next().val(parseInt($('.midmed b[pid="'+$(e.target).attr('proid')+'"]').next().val())+1);
                }else{
                    $('.midmed').append('<span><b pid="'+$(e.target).attr('proid')+'" isdrugstatus="'
                        +$(e.target).attr('isdrugstatus')+'" dataimg="'+
                        $(e.target).attr('dataimg')+'" dataprice="'+
                        $(e.target).attr('dataprice')+'" datamarket="'+
                        $(e.target).attr('datamarket')+'">'+$(e.target).parent().prev().prev().prev().prev().prev().text()
                        +'</b><input type="number" min="1" value="1"><a class="btn delbtn">删除</a></span>');

                }
                $('.delbtn').on('click',function (e) {
                    $(e.target).parent('span').remove();
                })
            });


        },
        error: function(err) {
            console.log(err)
        }
    });


})
//子分类信息
$('#category').change(function () {
    $('#p_store').html('<option value="">-子分类-</option>')
    for(var i=0;i<category.length;i++){
        if(category[i].categoryid==$('#category').val()){
            if(category[i].children.length>0){
                for(var j=0;j<category[i].children.length;j++){
                    $('#p_store').append('<option value="'+category[i].children[j].categoryid+'">'+category[i].children[j].categoryname+'</option>')
                }
            }else{
                $('#p_store').append('<option value=""></option>')
            }
        }
    }
});
//搜索产品
$('.search_product').on('click',function () {
	$('.pageindex_p').val(1)
    selectpro();
});
$('.search-index_p').on('click',function () {
    selectpro();
});
$('.prepage_p').on('click',function (e) {
    if(parseInt($('.pageindex_p').val())-1<1){

    }else{
        $('.pageindex_p').val(parseInt($('.pageindex_p').val())-1);
        selectpro();
    }

});
$('.nextpage_p').on('click',function (e) {
    if(parseInt($('.pageindex_p').val())+1>parseInt($(e.target).parent().next().children().text())){

    }else{
        $('.pageindex_p').val(parseInt($('.pageindex_p').val())+1);
        selectpro();
    }
    selectpro();
});
//生成诊断单
$('.savebtn').on('click',function (e) {
    console.log(doclist);
    var span=$('.medic span b');
    var medlist=[];
    for(var i=0;i<span.length;i++){
        medlist[i]={
            productid:$(span[i]).attr('pid'),
            productname:$(span[i]).text(),
            isdrugstatus: $(span[i]).attr('isdrugstatus'),
            count:$(span[i]).next('input').val(),
            marketprice:$(span[i]).attr('datamarket'),
            img:$(span[i]).attr('dataimg'),
            costprice:$(span[i]).attr('dataprice'),
        }
    }
    if($('textarea').val().length>500){
        alert('内容过长！')
    }else{
        if($.trim($('textarea').val())==""){
            alert('诊断结果不能为空')
        }else{
            var socketlist=[];
            for(var j=0;j<doclist.length;j++){
                if(parseInt(doclist[j].userrole)==4){
                    socketlist.push(doclist[j].id);
                }
            }
            socket.emit("private_msg", {
                socket_id:socketlist,
            });
            $.ajax({
                url:url+'/server/createCertificate',
                type:'post',
                data:{
                    _id: $(e.target).attr('listid'),
                    userRole: msg.userrole,
                    id: msg.userid,
                    name: msg.username,
                    diagnosisResult:$('textarea').val(),
                    medicinal: JSON.stringify(medlist),
                },
                headers: {
                    'Authorization': 'Bearer ' + msg.token
                },
                success:function (data) {
                    console.log(data);
                    if(data.code==200){
                        alert(data.mes);
                        $.ajax({
                            url:url+'/server/assDocPending',
                            type:'post',
                            data:{
                                id: msg.userid,
                                userRole: msg.userrole
                            },
                            headers: {
                                'Authorization': 'Bearer ' + msg.token
                            },
                            success:function (data2) {
                                console.log(data2);
                                window.top.document.getElementsByClassName('unfinish')[0].innerHTML=data2.data.length;
                                // $('.unfinish').text(data2.data.length)
                                if(data2.data.length>0){
                                    window.top.document.getElementsByClassName('unfinish')[0].style.display='inline-block';
                                }else{
                                    window.top.document.getElementsByClassName('unfinish')[0].style.display='none';
                                }
                                if(data2.code==200){
                                    $.ajax({
                                        url:url+'/service/modification',
                                        type:'post',
                                        data:{
                                            roomname:$(e.target).attr('userid'),
                                            state:'药师审核中'
                                        },
                                        headers: {
                                            'Authorization': 'Bearer ' + msg.token
                                        },
                                        success:function (data3) {
                                            console.log(data3);
                                            self.location='postpaper.html?detailId='+$(e.target).attr('listid')+'&&stauts=1';
                                        }
                                    })
                                }else{
                                    alert(data2.mes)
                                }
                            }
                        });

                    }else{
                        alert('操作失败')
                    }
                }
            });
        }
    }
});
//在线医生信息
socket.on("userlogin", function (data) {
    $(".doctor_select").children("option").remove();
    doclist=data.userlist;
    var userinfo = data.userlist;
    console.log(userinfo);
    socketuser=userinfo;
    var html2 = "";
    console.log(data)
    if (data.userlist.length != 0) {
        $.ajax({
            url:url+'/service/onlindoctor',
            type:'post',
            headers: {
                'Authorization': 'Bearer ' + msg.token
            },
            success:function (d) {
                console.log(d);
                for(var k=0;k<d.content.length;k++){
                    for (var a = 0; a < userinfo.length; a++) {
                        if ((userinfo[a].userrole == 1)&&(userinfo[a].name==d.content[k].userName)) {
                            html2 += '<option value="'+ d.content[k]._id +'" socketid="'+userinfo[a].id+'">'+ d.content[k].classifyId+'-'+d.content[k].classifyIdTwo+'-'+ d.content[k].userName + '</option>';//医生信息
                        }

                    };
                }
                $(".doctor_select").html(html2);
            }
        });
    }
});
//撤回指派
socket.on("Undo", function(data2) {
    console.log(data2, 222)
    window.top.document.getElementsByClassName('unfinish')[0].innerHTML =
        parseFloat(window.top.document.getElementsByClassName('unfinish')[0].innerHTML) - 1;
    if(parseFloat(window.top.document.getElementsByClassName('unfinish')[0].innerHTML) > 0) {
        window.top.document.getElementsByClassName('unfinish')[0].style.display = 'inline-block';
    } else {
        window.top.document.getElementsByClassName('unfinish')[0].style.display = 'none';
    }
    alert(data2.name+"撤回指派")
})
socket.on('inviteroom',function (data) {
    console.log(data);
    window.top.document.getElementsByClassName('invitelist')[0].innerHTML=
        parseFloat(window.top.document.getElementsByClassName('invitelist')[0].innerHTML)+1;
    window.top.document.getElementsByClassName('invitelist')[0].style.display='inline-block';
    $.ajax({
        url: url + '/service/inviteroom',
        type: 'post',
        data: {
            id: msg.userid,
            roomID: data.roomID,
            time: data.time,
            username: data.username,
            state: 0,
            socket_id: data.socket_id,
            roomname: data.roomname
        },
        headers: {
            'Authorization': 'Bearer ' + msg.token
        },
        success: function (d) {
        }
    })
})


//审核不通过通知消息
socket.on("notthrough_msg",function(data){
    console.log(data.msg+data._id[0]);
    var bottom=-200;
    var timer=setInterval(function () {
        bottom+=4;
        window.top.document.getElementById('msgnew').style.bottom=bottom+'px';
        window.top.document.getElementsByClassName('newmsg')[0].innerHTML='审核不通过';
        if(bottom>0){
            clearInterval(timer);
        }
    },47)
    window.top.document.getElementsByClassName('unfinish')[0].innerHTML=
        parseFloat(window.top.document.getElementsByClassName('unfinish')[0].innerHTML)+1;
    window.top.document.getElementsByClassName('unfinish')[0].style.display='inline-block';
})
//撤回邀请
socket.on("UndoInvite", function(data) {
    window.top.document.getElementsByClassName('invitelist')[0].innerHTML =
        parseFloat(window.top.document.getElementsByClassName('invitelist')[0].innerHTML) - 1;
    if(parseFloat(window.top.document.getElementsByClassName('invitelist')[0].innerHTML) > 0) {
        window.top.document.getElementsByClassName('invitelist')[0].style.display = 'inline-block';
    } else {
        window.top.document.getElementsByClassName('invitelist')[0].style.display = 'none';
    }
});
socket.on('private_msg', function(data) {
    console.log(data);
    window.top.document.getElementsByClassName('unfinish2')[0].innerHTML =
        parseFloat(window.top.document.getElementsByClassName('unfinish2')[0].innerHTML) + 1;
    window.top.document.getElementsByClassName('unfinish2')[0].style.display = 'inline-block';
})
socket.on('inviteroomss',function (data) {
    console.log(data);
    if(data.content==false){
        window.top.document.getElementsByClassName('invitelist')[0].innerHTML=
            parseFloat(window.top.document.getElementsByClassName('invitelist')[0].innerHTML)-1;
        if(parseFloat(window.top.document.getElementsByClassName('invitelist')[0].innerHTML)>0){
            window.top.document.getElementsByClassName('invitelist')[0].style.display='inline-block';
        }else{
            window.top.document.getElementsByClassName('invitelist')[0].style.display='none';
        }
    }
});
socket.on('assigndoctor',function (data) {
    console.log(data);
    $.ajax({
        url: url + '/server/assDocPending',
        type: 'post',
        data: {
            id: msg.userid,
            userRole: msg.userrole
        },
        headers: {
            'Authorization': 'Bearer ' + msg.token
        },
        success: function (data) {
            console.log(data);
            if (data.code == 200) {
                window.top.document.getElementsByClassName('unfinish')[0].innerHTML = data.data.length;
                // $('.unfinish').text(data.data.length)
                if (data.data.length > 0) {
                    window.top.document.getElementsByClassName('unfinish')[0].style.display = 'inline-block';
                } else {
                    window.top.document.getElementsByClassName('unfinish')[0].style.display = 'none';
                }
            } else {
                alert(data.mes)
            }
        }
    });
})
socket.on('private_msg', function(data) {
    console.log(data);
    if(msg.userrole==4){
        socket.on('private_msg', function(data) {
            console.log(data);
            window.top.document.getElementsByClassName('unfinish2')[0].innerHTML =
                parseFloat(window.top.document.getElementsByClassName('unfinish2')[0].innerHTML) + 1;
            window.top.document.getElementsByClassName('unfinish2')[0].style.display = 'inline-block';
        })
    }else{
        window.top.document.getElementsByClassName('unfinish')[0].innerHTML =
            parseFloat(window.top.document.getElementsByClassName('unfinish')[0].innerHTML) + 1;
        window.top.document.getElementsByClassName('unfinish')[0].style.display = 'inline-block';
    }
})
//指派医生
$('.savedoc').on('click',function (e) {
    console.log('aa');
        var span=$('.medic span b');
        var medlist=[];
        for(var i=0;i<span.length;i++){
            medlist[i]={
                productid:$(span[i]).attr('pid'),
                productname:$(span[i]).text(),
                isdrugstatus: $(span[i]).attr('isdrugstatus'),
                count:$(span[i]).next('input').val()
            }
        }
    socket.emit("private_msg", {
        socket_id:$('.doctor_select option:selected').attr('socketid'),
    });
        $.ajax({
            url:url+'/server/assSendDoc',
            type:'post',
            data:{
                _id: $(e.target).attr('listid'),
                userRole: msg.userrole,
                doctorId: $('.doctor_select').val(),
                doctorName: $('.doctor_select option:selected').text(),
                assMedicinal: JSON.stringify(medlist),
            },
            headers: {
                'Authorization': 'Bearer ' + msg.token
            },
            success:function (data) {
                console.log(data);
                if(data.code==200){
                    alert(data.mes);
                    window.top.document.getElementsByClassName('unfinish')[0].innerHTML=
                        parseFloat(window.top.document.getElementsByClassName('unfinish')[0].innerHTML)-1;
                    if(parseFloat(window.top.document.getElementsByClassName('unfinish')[0].innerHTML)>0){
                        window.top.document.getElementsByClassName('unfinish')[0].style.display='inline-block';
                    }else{
                        window.top.document.getElementsByClassName('unfinish')[0].style.display='none';
                    }
                    self.location='../pages_doctor/html/finish.html'
                }else{
                    alert('操作失败');
                }
            }
        });
});
function compare (prop) {
    return function (obj1, obj2) {
        var val1 = obj1[prop];
        var val2 = obj2[prop];
        if (val1 < val2) {
            return -1;
        } else if (val1 > val2) {
            return 1;
        } else {
            return 0;
        }
    }
}
function selectpro() {
    $.ajax({
        type: "post",
        url: "https://xcxgoods.juseyx.cn/products/GetYyReceptionGoods",
        data:  {
            categoryid: $('#p_store').val(),
            pagesize: 7,
            pageindex: $('.pageindex_p').val(),
            ReceptionSearch: $('.p_name').val(),
            brandid: null,
            isdrugstatus: null,
            SortBy: "addeddate",
            Desc: true
        },
        success: function(res) {

            console.log(res);
            $('.p_list tbody').html('');
            if(res.data.length>0){
                for(var i=0;i<res.data.length;i++){
                    $('.p_list tbody').append('<tr><td>'+
                        res.data[i].productname+'</td><td><img  width="50px" height="50px" src="'+
                        res.data[i].goodlistimageurl+res.data[i].goodlistimagename+'" alt=""></td><td>'+
                        res.data[i].dosageformname +'</td><td>'+
                        res.data[i].brandname+'</td><td>'+
                        res.data[i].brandname+'</td>' +
                        '<td><span class="checkmed text-center" proid="'+res.data[i].productid+'" isdrugstatus="'+
                        res.data[i].isdrugstatus+'" dataimg="'+
                        res.data[i].goodlistimageurl+res.data[i].goodlistimagename+'" dataprice="'+
                        res.data[i].costprice+'" datamarket="'+
                        res.data[i].marketprice+'">+</span></td></tr>')
                }
                $('.pagecount_p').text(Math.ceil(res.datacount/7));
            }else{
                $('.p_list tbody').append('<tr><td colspan="6" class="text-center">未找到产品</td></tr>')
            }
            //确认选择商品
            $('.checkmed').on('click',function (e) {

                var lis=$('.midmed span b');
                var canpush=true;
                for(var i=0;i<lis.length;i++){
                    if($(lis[i]).attr('pid')==$(e.target).attr('proid')){
                        canpush=false;
                    }
                }
                if(canpush==false){
                    $('.midmed b[pid="'+$(e.target).attr('proid')+'"]').next().val(parseInt($('.midmed b[pid="'+$(e.target).attr('proid')+'"]').next().val())+1);
                }else{
                    $('.midmed').append('<span><b pid="'+$(e.target).attr('proid')+'" isdrugstatus="'
                        +$(e.target).attr('isdrugstatus')+'" dataimg="'+
                        $(e.target).attr('dataimg')+'" dataprice="'+
                        $(e.target).attr('dataprice')+'" datamarket="'+
                        $(e.target).attr('datamarket')+'">'+$(e.target).parent().prev().prev().prev().prev().prev().text()
                        +'</b><input type="number" min="1" value="1"><a class="btn delbtn">删除</a></span>');

                }
                $('.delbtn').on('click',function (e) {
                    $(e.target).parent('span').remove();
                })
            });
        },
        error: function(err) {
            console.log(err)
        }
    });
}
$('.choosemed').on('click',function () {
    $('.midmed').html($('.medic').html());
    var spanlist=$('.medic span b');
    for(var i=0;i<spanlist.length;i++){
        $($('.midmed span b')[i]).next().val(parseInt($(spanlist[i]).next().val()));
    }
    $('.delbtn').on('click',function (e) {
        $(e.target).parent('span').remove();
    })
});
$('.surecheck').on('click',function () {
    $('.medic').html($('.midmed').html());
    var spanlist=$('.midmed span b');
    for(var i=0;i<spanlist.length;i++){
        $($('.medic span b')[i]).next().val(parseInt($(spanlist[i]).next().val()));
    }
    $('.delbtn').on('click',function (e) {
        $(e.target).parent('span').remove();
    })
});
$('.del-med').on('click',function () {
    $('.medic').html('');
    $('.midmed').html('');
})
$('.search_empty').on('click',function () {
	$('.pageindex_p').val(1)
    $('#p_store').val('');
    $('.p_name').val('');
    $('#category').val('');
})

